﻿using System;
using System.Collections;
using System.Net;
using System.Security.Cryptography;

namespace HoNSharp
{
    public delegate void HoNLoginInfoEventHandler(object sender, HoNLoginInfoArgs e);

    public class HoNLoginInfoArgs : EventArgs
    {
        private bool success;
        private Hashtable data;

        public HoNLoginInfoArgs(bool LoggedIn, Hashtable info)
        {
            this.success = LoggedIn;
            this.data = info;
        }

        public bool LoggedIn()
        {
            return this.success;
        }

        public Hashtable Data()
        {
            return this.data;
        }
    }

    class HoNClientLogin
    {
        public event HoNLoginInfoEventHandler Login;

        protected virtual void OnLogin(HoNLoginInfoArgs e)
        {
            if (Login != null)
            {
                Login(this, e);
            }
        }

        private WebClient _wc;

        public HoNClientLogin()
        {
            this._wc = new WebClient();
        }

        private static string HashString(string val)
        {
            string md5Hash = "";
            MD5CryptoServiceProvider myCrypt = new MD5CryptoServiceProvider();
            byte[] md5out = System.Text.Encoding.ASCII.GetBytes(val);
            md5out = myCrypt.ComputeHash(md5out);
            for (int i = 0; i < md5out.Length; i++)
            {
                md5Hash += md5out[i].ToString("x2").ToLower();
            }
            return md5Hash;
        }

        private void ReceivedLoginData(Object sender, UploadDataCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null)
            {
                byte[] result = (byte[])e.Result;
                Hashtable accountInfo = (Hashtable)PHPSerializer.UnSerialize(result);
                if ((bool)accountInfo[0] != false)
                {
                    this.OnLogin(new HoNLoginInfoArgs(true, accountInfo));
                }
                else
                {
                    this.OnLogin(new HoNLoginInfoArgs(false, accountInfo));
                }
            }
        }

        public void DoLogin(string username, string password)
        {
            string loginData = "f=auth&login=" + username + "&password=" + HashString(password);
            byte[] postData = System.Text.Encoding.ASCII.GetBytes(loginData);
            this._wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            this._wc.UploadDataCompleted += new UploadDataCompletedEventHandler(ReceivedLoginData);
            this._wc.UploadDataAsync(new Uri("http://masterserver.hon.s2games.com/client_requester.php"), postData);
        }
    }
}
